import numpy as np
import os
import tecplot as tp
from tecplot.constant import *

#以szplt格式写出数据
def Writeszplt(fname,pixle_x,pixle_y,data,filename,time):
    width, height = pixle_y,pixle_x
    tp.new_layout()
    ds = tp.active_frame().create_dataset(filename, ['x', 'y'])
    strand = 1
    solution_time = time
    zone = ds.add_ordered_zone(filename + str(time), (width + 1, height + 1))

    zone.solution_time = solution_time
    zone.strand = strand
    xx = np.tile(np.arange(width + 1), height + 1)
    yy = np.repeat(np.arange(height + 1), width + 1)
    zone.values('x')[:] = xx
    zone.values('y')[:] = yy

    tp.data.operate.execute_equation("{T} = 0", value_location=ValueLocation.CellCentered)
    zonedata = np.c_[data, np.zeros(height)]
    zone.values('T')[:] = zonedata.flatten()

    tp.data.save_tecplot_szl(fname, dataset=ds)
    return 0

#以dat格式写出数据
def Writedat(fname,pixle_x,pixle_y,data,zonename):
    with open(fname,'w',encoding='utf-8') as file_obj:
        file_obj.write("TITLE=\"IR_Data\"\n")
        file_obj.write("VARIABLES=  \"x\" \"y\" \"T\"\n")
        file_obj.write("ZONE T=\"" + zonename +"\" I="+str(pixle_x)+" J="+str(pixle_y)+" F=POINT\t\n")
        for y in range(0,pixle_y):
            for x in range(0,pixle_x):
                file_obj.write("%d" % y+" %d" % x+" %f.6" % data[x][y]+"\n")
        file_obj.close
    return 0
                
#中间过程，通过温度计算电压，系数c1通过已有的数据标定得出
def U_T(T):
    c1 = 1/226
    return c1 * pow(T / sigma / eps, 0.25)

#计算物体辐射部分贡献的电压
def U_obj(U_tot, eps, tau, U_refl, U_atm):
    return U_tot/(eps*tau)-(1-eps)/eps*U_refl-((1-tau)/(eps*tau))*U_atm

#创建文件夹
def makedir(path):
    isExists = os.path.exists(path)
    if not isExists:
        os.mkdir(path)
    return 0

if __name__ == '__main__':
    ###1.路径参数
    #根目录
    root = r'C:\Users\HWW\Desktop\Flir_data'
    #要处理的文件名
    filename = 'Rec-V15_T-5_Steady_HLY-000054'
    #图像的像素大小
    pixle_x = 480
    pixle_y = 640
    #采集频率
    fs = 25
    
    ###2.热学参数
    #物体发射率
    eps = 0.83
    #介质的透射率
    tau = 1
    #反射温度
    Reflect_Temp = 273
    #大气温度
    Atm_Temp = 273
    
    ###3.导出参数
    #需要处理的帧，起始序号，终止序号以及步长
    Start_num = 0
    End_num = 100
    Step = 10
    
    #以下内容一般不需要修改
    #处理结果将存放在与文件名同名的文件夹内
    makedir(os.path.join(root,filename))
    makedir(os.path.join(root,filename,'Data'))
    f = open(file=os.path.join(root,filename+'.seq'),mode='rb')
    data = f.read()
    f.close
    
    #a是起始行，b是图片数据结束后的空行
    a = 2780
    b = 2652
    
    #传感器电压
    U_tot = 4.5
    #斯特藩-玻尔兹曼常数
    sigma = 5.670374419e-8
    #标定系数U_tot4.5:4.53~4.6,U_tot5.0:4.36~4.46
    c = 4.41
    # Reflect_Temp,反射温度
    U_refl = U_T(Reflect_Temp)
    # Atm_Temp,大气温度
    U_atm = U_T(Atm_Temp)

    for k in range(Start_num, End_num, Step):
        startline = a+k*(pixle_x*pixle_y*2+b)
        Im = np.zeros((pixle_x,pixle_y))
        U = np.zeros((pixle_x,pixle_y))
        T = np.zeros((pixle_x,pixle_y))
    
        for i in range(pixle_x):
            for j in range(pixle_y):
                index = startline+i*pixle_y*2+j*2
                Im[i][j] = int(str(bin(data[index+1]))+str(bin(data[index])[2:].zfill(8)),2)
                #Im[i][j]=int(data[index]*1+data[index+1]*255)#两种方法都可以，结果非常接近
                
                U[i][j] = U_obj(Im[i][j]/pow(2,16)*U_tot,eps,tau,U_refl,U_atm)
                T[i][j] = c * pow(U[i][j] / sigma / eps, 0.25)
        
        #导出dat格式，如果选的导出该格式，取消注释下面这一行代码即可
        #Writedat(os.path.join(root,filename,'Data',filename + '_' + str(k) +'.dat'), pixle_x, pixle_y, T, filename +'_'+str(k/fs))
        
        #导出szplt格式，文件小，读取速度快
        Writeszplt(os.path.join(root,filename,'Data', filename + '_' + str(k) +'.szplt'), pixle_x, pixle_y, T, filename, k/fs)
    



